import 'dart:io';

import 'package:bot_toast/src/basis.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:freedom/entity/restful.dart';
import 'package:freedom/util/api_router.dart';
import 'package:freedom/util/data_type.dart';
import 'package:freedom/util/http.dart';
import 'package:freedom/util/insert_home.dart';
import 'package:freedom/util/paging_easy_refresh.dart';
import 'package:freedom/widget/common_alter_dialog.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

typedef BuildFunc = Widget Function(dynamic data);

class HoomRecordHistoryDialog extends StatefulWidget {
  final CancelFunc cancelFunc;
  const HoomRecordHistoryDialog(this.cancelFunc, {super.key});

  @override
  RecordDialogState createState() => RecordDialogState();
}

class RecordDialogState extends State<HoomRecordHistoryDialog> {
  // 选项高度
  double itemHeight = 70.h;
// 标题高度
  double roomInfoHeight = 20.h;
  // 头像高度
  double headHeight = 40.h;
  // 文字大小
  double fontSize = 12.h;

  bool child = false;
  String? _selectRoomId;
  String? _selectRoomType;

  List childrenData = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CommonAlterDialog(
      closeWindow: widget.cancelFunc,
      backgroundColor: const Color.fromARGB(255, 255, 255, 255),
      child: Container(
          margin: EdgeInsets.all(10.h),
          child: Column(
            children: [
              Container(
                height: 30.h,
                width: double.infinity,
                alignment: Alignment.centerLeft,
                margin: EdgeInsets.only(bottom: 5.h),
                color: const Color.fromARGB(255, 167, 216, 245),
                child: Row(
                  children: [
                    SizedBox(
                      width: 10.h,
                    ),
                    InkWell(
                      onTap: () {
                        if (!child) {
                          widget.cancelFunc();
                        }
                        child = false;
                        setState(() {});
                      },
                      child: Icon(
                        Icons.arrow_back,
                        color: Colors.white,
                        size: 20.h,
                      ),
                    ),
                    SizedBox(
                      width: 10.h,
                    ),
                    Text(
                      "选择日期:",
                      style: TextStyle(
                          color: Colors.white,
                          height: 1.0,
                          fontSize: fontSize,
                          fontWeight: FontWeight.bold),
                    ),
                    const Expanded(child: SizedBox()),
                    Icon(
                      Icons.switch_video,
                      color: Colors.white,
                      size: 20.h,
                    ),
                    SizedBox(
                      width: 5.h,
                    ),
                    Text(
                      "查看他人回放",
                      style: TextStyle(
                          decoration: TextDecoration.underline,
                          decorationStyle: TextDecorationStyle.solid,
                          decorationThickness: 2,
                          decorationColor: Colors.white,
                          color: Colors.white,
                          height: 1.0,
                          fontSize: fontSize,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      width: 10.h,
                    ),
                  ],
                ),
              ),
              Expanded(
                  child: child
                      ? ListView(
                          children: childrenData
                              .map((e) =>
                                  recordItem(e, buildChildUtil, parent: false))
                              .toList(),
                        )
                      : AnimatedContainer(
                          duration: const Duration(seconds: 1),
                          onEnd: () {},
                          child: ClipRect(
                            child: PagingEasyRefresh(
                              key: GlobalKey(),
                              url: ApiRouter.historyRecode,
                              buildItem: (item) {
                                return recordItem(item, buildMainUtil);
                              },
                            ),
                          ),
                        ))
            ],
          )),
    );
  }

  Widget buildMainUtil(dynamic data) {
    String roomId = data["roomId"] != null ? data["roomId"].toString() : "0";
    String roomType = data["type"] != null ? data["type"].toString() : "0";
    return SizedBox(
      width: itemHeight,
      height: itemHeight,
      child: MaterialButton(
          splashColor: Colors.orange,
          minWidth: itemHeight,
          onPressed: () {
            _selectRoomId = roomId;
            _selectRoomType = roomType;
            Http.getInstance().request<Restful>(ApiRouter.historyRecodeList,
                contentType: ContentType.json,
                data: {"roomId": _selectRoomId}, success: (data) {
              child = true;
              if (data.body is List) {
                childrenData = asT<List>(data.body) ?? [];
              }
              setState(() {});
            });
          },
          child: const Center(child: Icon(Icons.arrow_forward_ios))),
    );
  }

  Widget buildChildUtil(dynamic data) {
    return SizedBox(
      height: itemHeight,
      width: itemHeight * 2,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          SizedBox(
              height: itemHeight,
              width: itemHeight,
              child: MaterialButton(
                  splashColor: Colors.amber,
                  onPressed: () {},
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        "assets/images/system/share.png",
                        height: fontSize * 2,
                        fit: BoxFit.cover,
                      ),
                      Text(
                        "分享",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Colors.blue,
                            fontSize: fontSize,
                            height: 1.0,
                            fontWeight: FontWeight.w600),
                      )
                    ],
                  ))),
          SizedBox(
              height: itemHeight,
              width: itemHeight,
              child: MaterialButton(
                  splashColor: Colors.orange,
                  minWidth: itemHeight,
                  onPressed: () {
                    var severalInning = data["severalInning"];
                    Http.getInstance().request<Restful>(
                        ApiRouter.historyRecodeInfo,
                        contentType: ContentType.json,
                        showLoading: true,
                        loadingMsg: "加载中...",
                        data: {
                          "roomId": _selectRoomId,
                          "severalInning": severalInning
                        }, success: (data) {
                      InsertHome.addHome(context, _selectRoomType!, "",
                          record: data.body);
                    });
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        "assets/images/system/videotape.png",
                        height: fontSize * 2,
                        fit: BoxFit.cover,
                      ),
                      Text(
                        "回放",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            color: Colors.orange,
                            fontSize: fontSize,
                            height: 1.0,
                            fontWeight: FontWeight.w600),
                      )
                    ],
                  ))),
        ],
      ),
    );
  }

  Widget recordItem(dynamic data, BuildFunc funcBuild, {bool parent = true}) {
    String roomCode = data["code"] ?? "未知";
    String startDate = data["createDate"] ?? "未知";
    String roomType = data["name"] ?? "未知";
    String severalInning =
        data["severalInning"] != null ? data["severalInning"].toString() : "0";
    List allUsers = data["allUsers"] is List ? data["allUsers"] : [];
    return Container(
      height: itemHeight,
      padding: EdgeInsets.all(5.h),
      margin: EdgeInsets.only(bottom: 5.w),
      decoration: BoxDecoration(
          color: Colors.black.withOpacity(0.1),
          borderRadius: BorderRadius.circular(10.h)),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: roomInfoHeight,
                child: ListView(
                  padding: const EdgeInsets.all(0),
                  scrollDirection: Axis.horizontal,
                  children: [
                    parent
                        ? textContainer("房间类型:", roomType)
                        : const SizedBox(),
                    parent ? textContainer("房间号:", roomCode) : const SizedBox(),
                    parent
                        ? const SizedBox()
                        : textContainer("当前局数:", severalInning),
                    textContainer("开始时间:", startDate),
                  ],
                ),
              ),
              SizedBox(
                  height: headHeight,
                  child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      child: Row(
                        children: allUsers
                            .map((item) => userWidget(
                                item["username"],
                                item["portraitUrl"],
                                item["score"] != null
                                    ? item["score"].toString()
                                    : "0"))
                            .toList(),
                      )))
            ],
          )),
          funcBuild(data)
        ],
      ),
    );
  }

  Container userWidget(String name, String? headImg, String fraction) {
    return Container(
        width: headHeight * 2,
        height: headHeight,
        alignment: Alignment.center,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(1.h),
        ),
        child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ClipRRect(
                  borderRadius: BorderRadius.circular(3.w),
                  child: SizedBox(
                    height: 30.h,
                    width: 30.h,
                    child: headImg == null
                        ? Image.asset(
                            "assets/images/mahjong/user/header/common_header.png",
                            fit: BoxFit.cover,
                          )
                        : CachedNetworkImage(
                            fit: BoxFit.cover,
                            height: headHeight,
                            width: headHeight,
                            placeholder: (context, url) =>
                                const CircularProgressIndicator(),
                            errorWidget: (context, url, error) =>
                                const Icon(Icons.error),
                            imageUrl: headImg,
                          ),
                  )),
              Expanded(
                  child: SizedBox(
                      child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(fraction,
                      style: TextStyle(
                          color: Colors.red,
                          fontSize: fontSize,
                          height: 1.0,
                          fontWeight: FontWeight.w600)),
                  Text(name,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          color: Colors.black,
                          height: 1.0,
                          fontSize: fontSize)),
                ],
              )))
            ]));
  }

  Row textContainer(String title, String context) {
    return Row(
      children: [
        Text(
          title,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style:
              TextStyle(color: Colors.black, height: 1.0, fontSize: fontSize),
        ),
        SizedBox(
          width: 5.w,
        ),
        Container(
          height: 18.h,
          alignment: Alignment.center,
          padding: EdgeInsets.symmetric(horizontal: 5.w),
          decoration: BoxDecoration(
              color: Colors.orange, borderRadius: BorderRadius.circular(5.w)),
          child: Text(
            context,
            textAlign: TextAlign.center,
            style: TextStyle(
                color: Colors.white,
                height: 1.0,
                fontSize: fontSize,
                fontWeight: FontWeight.bold),
          ),
        ),
        SizedBox(
          width: 5.w,
        ),
      ],
    );
  }
}
